package com.jun2yah.quiz;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 영어 단어 퀴즈를 내면 한글 뜻을 맞추는 퀴즈
 * 
 * com.jun2yah.quiz
 * Quiz.java
 *
 * @author junhwan_kim
 * @date 2011. 6. 2. 오후 12:17:50
 * @Version
 */
public class Quiz extends Activity {
	
	Context context = Quiz.this;
	
	private DatabaseHelper mHelper = null;
	private Cursor mCursor = null;
	
	ProgressBar progress;
	TextView textTime;
	
	private static final int SECOND = 10;
	private static final int INCREMENT_PROGRESS_BY = 10;
	private static final int SLEEP_TIME = (SECOND * 1000) / (100 / INCREMENT_PROGRESS_BY);
	
	String[][] word;	// db에서 받아오는 자료
	String[] KorA;		// 4개 정답
	int btnCorrect;		// 어떤것이 정답인지 정하는 변수
	int stepQ = 0;		// 몇번째 문제인지
	int score = 0;		// 몇문제 맞추었는지
	
	public static int NUM_WORDS = 0;		// db에 저장된 단어수 
	
	boolean isRunning = false;	// Timer Toggle
	int timeRemain = SECOND;
	ImageView imgO, imgX;
	
	Button btn1;
	Button btn2;
	Button btn3;
	Button btn4;
	
	/**
	 * SQLite의 DB를 Select하여 퀴즈를 낸다.
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 * @Method onCreate
	 * @param savedInstanceState
	 *
	 * @author junhwan_kim
	 * @date 2011. 6. 2. 오후 12:20:00
	 */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mHelper = new DatabaseHelper(this);
        
        /// DB를 assets에서 sdcard로 복사한다.
        mHelper.copyDB(context);
        
        /// DB에서 data를 가져온다.
		mCursor = mHelper.getWritableDatabase().rawQuery("SELECT no, " + 
				DatabaseHelper.WORD + ", " + 
				DatabaseHelper.MEAN + " FROM " + 
				DatabaseHelper.TABLE_NAME, null);
		
		NUM_WORDS = mCursor.getCount();
		
		/// db에서 가져온 자료 저장할 배열
		word = new String[NUM_WORDS][3];

		/// DB Select
		if (mCursor != null) {
			if (mCursor.moveToFirst()) {
				String strRow = "----------------------------\n";
//				for (int i = 0; i < mCursor.getColumnCount(); i++) {
//					strRow += mCursor.getColumnName(i) + "|";
//				}
//				strRow += "\n";
//				Log.i("jhkim", strRow);
				
				
				int count = 0;
				
				do {
					strRow = "";
					for (int i = 0; i < mCursor.getColumnCount(); i++) {
						strRow += mCursor.getString(i) + "|";
						word[count][i] = mCursor.getString(i);
					}
					strRow += "\n";
					Log.i("jhkim", strRow);
					count++;
				} while (mCursor.moveToNext());
			}
		}
		
		// 몇번 문제인지 & 점수 count
		Intent intent = getIntent();
		stepQ = intent.getIntExtra("Step", 0);
		score = intent.getIntExtra("Score", 0);
		
		String engQ = word[stepQ][1];
		
        Random random = new Random();
        
        int num1 = random.nextInt(10);
        while (stepQ == num1) {
        	num1 = random.nextInt(10);
        	if (stepQ != num1) break;
        }
        
        int num2 = random.nextInt(10);
        while ((stepQ == num2) || (num1 == num2)) {
        	num2 = random.nextInt(10);
        	if ((stepQ != num2) && (num1 != num2)) break;
        }
        
        int num3 = random.nextInt(10);
        while ((stepQ == num3) || (num1 == num3) || (num2 == num3)) {
        	num3 = random.nextInt(10);
        	if ((stepQ != num3) && (num1 != num3) && (num2 != num3)) break;
        }
        
        /// 정답 순서 정하기
        int[] ans_num = new int[4];
        ans_num[0] = random.nextInt(4);
        
        ans_num[1] = random.nextInt(4);
        while (ans_num[0] == ans_num[1]) {
        	 ans_num[1] = random.nextInt(4);
        	if (ans_num[0] != ans_num[1]) break;
        }
        
        ans_num[2] = random.nextInt(4);
        while ((ans_num[0] == ans_num[2]) || (ans_num[1] == ans_num[2])) {
        	ans_num[2] = random.nextInt(4);
        	if ((ans_num[0] != ans_num[2]) && (ans_num[1] != ans_num[2])) break;
        }
        
        ans_num[3] = random.nextInt(4);
        while ((ans_num[0] == ans_num[3]) || (ans_num[1] == ans_num[3]) || (ans_num[2] == ans_num[3])) {
        	ans_num[3] = random.nextInt(4);
        	if ((ans_num[0] != ans_num[3]) && (ans_num[1] != ans_num[3]) && (ans_num[2] != ans_num[3])) break;
        }
        
        KorA = new String[4];
        KorA[0] = word[stepQ][2];
        KorA[1] = word[num1][2];
        KorA[2] = word[num2][2];
        KorA[3] = word[num3][2];
        
        /// 정답 선택에 따른 O, X
        imgO = (ImageView)findViewById(R.id.imgO);
        imgX = (ImageView)findViewById(R.id.imgX);
        
        /// 처음엔 O, X를 숨긴다.
        imgX.setVisibility(View.INVISIBLE);
        imgO.setVisibility(View.INVISIBLE);
        
        /// English Question Text 
        TextView textQuestion = (TextView)findViewById(R.id.textQuestion);
        textQuestion.setText(engQ);
        
        /// 현재 문제 Step을 표시
        TextView textStep = (TextView)findViewById(R.id.textStep);
        textStep.setText(String.valueOf(stepQ + 1) + "/" + NUM_WORDS);
        
        /// Answer1 버튼의 Listener
        btn1 = (Button)findViewById(R.id.btnAnswer01);
        btn1.setText(KorA[ans_num[0]]);
        btn1.setOnClickListener(mClickListener);
        
        /// Answer2 버튼의 Listener
        btn2 = (Button)findViewById(R.id.btnAnswer02);
        btn2.setText(KorA[ans_num[1]]);
        btn2.setOnClickListener(mClickListener);
        
        /// Answer3 버튼의 Listener
        btn3 = (Button)findViewById(R.id.btnAnswer03);
        btn3.setText(KorA[ans_num[2]]);
        btn3.setOnClickListener(mClickListener);
        
        /// Answer4 버튼의 Listener
        btn4 = (Button)findViewById(R.id.btnAnswer04);
        btn4.setText(KorA[ans_num[3]]);
        btn4.setOnClickListener(mClickListener);
        
        /// 정답이 몇번인지 btnCorrect에 저장
        for (int i = 0; i < 4; i++) {
        	if (ans_num[i] == 0) {
            	btnCorrect = i;
            	break;
            }
        }

        progress = (ProgressBar)findViewById(R.id.progress);
        
        textTime = (TextView)findViewById(R.id.textTime);
        textTime.setText("" + SECOND);
    }
    
    /**
     * Button click listener
     */
    Button.OnClickListener mClickListener = new Button.OnClickListener() {

		public void onClick(View v) {
			
			switch (v.getId()) {
			case R.id.btnAnswer01:
				if (btnCorrect == 0) {
					imgO.setVisibility(View.VISIBLE);
					imgX.setVisibility(View.INVISIBLE);
					score++;
//					String countS = Preferences.getCount(context);
//					Preferences.setCount(context, countO);
				} else {
					imgO.setVisibility(View.INVISIBLE);
					imgX.setVisibility(View.VISIBLE);
				}
				isRunning = false;
				break;
			case R.id.btnAnswer02:
				if (btnCorrect == 1) {
					imgO.setVisibility(View.VISIBLE);
					imgX.setVisibility(View.INVISIBLE);
					score++;
				} else {
					imgO.setVisibility(View.INVISIBLE);
					imgX.setVisibility(View.VISIBLE);
				}
				isRunning = false;
				break;
			case R.id.btnAnswer03:
				if (btnCorrect == 2) {
					imgO.setVisibility(View.VISIBLE);
					imgX.setVisibility(View.INVISIBLE);
					score++;
				} else {
					imgO.setVisibility(View.INVISIBLE);
					imgX.setVisibility(View.VISIBLE);
				}
				isRunning = false;
				break;
			case R.id.btnAnswer04:
				if (btnCorrect == 3) {
					imgO.setVisibility(View.VISIBLE);
					imgX.setVisibility(View.INVISIBLE);
					score++;
				} else {
					imgO.setVisibility(View.INVISIBLE);
					imgX.setVisibility(View.VISIBLE);
				}
				isRunning = false;
				break;
			}
			
			switch(btnCorrect) {
			case 0:
				btn1.setTextColor(Color.RED);
				btn1.setTextSize(20);
				break;
			case 1:
				btn2.setTextColor(Color.RED);
				btn2.setTextSize(20);
				break;
			case 2:
				btn3.setTextColor(Color.RED);
				btn3.setTextSize(20);
				break;
			case 3:
				btn4.setTextColor(Color.RED);
				btn4.setTextSize(20);
				break;
			}
			
			/// 버튼 비활성화
			btn1.setClickable(false);
			btn2.setClickable(false);
			btn3.setClickable(false);
			btn4.setClickable(false);
			
			/// 1초 후에 다음 단계로 넘어간다.
			NextStep nextW = new NextStep();
	        Timer timerS = new Timer(false);
	        timerS.schedule(nextW, 1000);
		}
    };
    
    /**
     * onCreate() 이후 수행되는 Activity 생명주기 Method
     * 
     * @see android.app.Activity#onStart()
     * @Method onStart
     *
     * @author junhwan_kim
     * @date 2011. 6. 2. 오후 12:21:11
     */
    @Override
    protected void onStart() {
    	super.onStart();
    	
    	/// ProgresBar 0으로 초기화
    	progress.setProgress(0);
    	
    	/// Timer를 돌려서 ProgressBar를 증가 시킨다.
    	Thread background = new Thread(new Runnable() {
			public void run() {
				try {
					for (int i = 0; i < (100 / INCREMENT_PROGRESS_BY) && isRunning; i++) {
						Thread.sleep(SLEEP_TIME);
						handler.sendMessage(handler.obtainMessage());
						timeRemain--;
					}
				} catch (Throwable t) {}
			}
    	});
    	
    	isRunning = true;
    	background.start();
    }
    
    /**
     * Activity가 View에서 사라졌을 때 불리는 Method
     * 
     * @see android.app.Activity#onStop()
     * @Method onStop
     *
     * @author junhwan_kim
     * @date 2011. 6. 2. 오후 12:22:44
     */
    @Override
    protected void onStop() {
    	super.onStop();
    	isRunning = false;
    }
    
    /**
     * Activity가 종료될 때 불리는 Method
     * 
     * @see android.app.Activity#onDestroy()
     * @Method onDestroy
     *
     * @author junhwan_kim
     * @date 2011. 6. 2. 오후 12:25:40
     */
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	
    	mCursor.close();
		mHelper.close();
    }
    
    /**
	 * 뒤로가기 버튼 이벤트 
	 * 어떤 이벤트도 일어나지 않도록한다.
	 * 
	 * @see android.app.Activity#onBackPressed()
	 * @Method onBackPressed
	 *
	 * @author jun2yah
	 * @date 2011. 6. 10. 오후 10:53:55
	 */
    @Override
    public void onBackPressed() {}
    
    /**
	 * 몇 초 후에 다음 단어 or 결과로 넘어간다.
	 * com.jun2yah.quiz
	 * Quiz.java
	 *
	 * @author junhwan_kim
	 * @date 2011. 6. 8. 오후 5:13:50
	 * @Version
	 */
	class NextStep extends TimerTask {
		@Override
		public void run() {
			if (stepQ < NUM_WORDS - 1) {
				Intent intent = new Intent(Quiz.this, Quiz.class);
				intent.putExtra("Step", ++stepQ);
				intent.putExtra("Score", score);
				startActivity(intent);
			} else {
				Intent intent = new Intent(Quiz.this, Result.class);
				intent.putExtra("NumOfWords", NUM_WORDS);
				intent.putExtra("Score", score);
				startActivity(intent);
			}
		}
	}
	
	/**
	 * ProgressBar를 증가 시키는 Handler
	 */
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			progress.incrementProgressBy(INCREMENT_PROGRESS_BY);
			
			textTime.setText(String.valueOf(timeRemain));
			
			if (progress.getProgress() == 100) {
				imgO.setVisibility(View.INVISIBLE);
				imgX.setVisibility(View.VISIBLE);
				
				/// 1초 후에 다음 단계로 넘어간다.
				NextStep nextW = new NextStep();
		        Timer timerS = new Timer(false);
		        timerS.schedule(nextW, 1000);
			}
		}
	};
}